#include "ctimesynchronizer.h"

CTimeSynchronizer* CTimeSynchronizer::instance;

/**
 * CTimeSynchronizer - sets default values
 */
CTimeSynchronizer::CTimeSynchronizer() {
  instance = NULL;
  frameInterval = 0.0f;
  frameTime = 0.0f;
  fps = 0.0f;
  lastTime = 0.0f;
}
//---------------------------------------------------------------------------

/**
 * ~CTimeSynchronizer - destroys instance
 */
CTimeSynchronizer::~CTimeSynchronizer() {
  freeInstance();
}
//---------------------------------------------------------------------------

/**
 * getFrameInterval - returns interval before two frames (redraws of display)
 * @return interval
 */
double CTimeSynchronizer::getFrameInterval() const {
  return frameInterval;
}
//---------------------------------------------------------------------------

/**
 * getFrameTime - returns time consumed for last redraw
 * @return time
 */
double CTimeSynchronizer::getFrameTime() const {
  return frameTime;
}
//---------------------------------------------------------------------------

/**
 * getFPS - returns current FPS
 * @return number of frames per second
 */
int CTimeSynchronizer::getFPS() const {
  return (int)fps;
}
//---------------------------------------------------------------------------

/**
 * update - calculates new frameInterval and FPS
 * @param time
 */
void CTimeSynchronizer::update(double time) {
  double currentTime(time * 0.001f);
  frameInterval = currentTime - frameTime;
  frameTime = currentTime;
  ++tmpFps;

  if (currentTime - lastTime > 1.0f) {
    lastTime = currentTime;
    fps = tmpFps;
    tmpFps = 0.0f;
  }
}
//---------------------------------------------------------------------------

/**
 * getInstance - returns pointer to instance
 * @return pointer to instance
 */
CTimeSynchronizer* CTimeSynchronizer::getInstance() {
  if (!instance) {
    instance = new CTimeSynchronizer();
  }
  return instance;
}
//---------------------------------------------------------------------------

/**
 * freeInstance - deletes instance
 */
void CTimeSynchronizer::freeInstance() {
  if (instance) {
    delete instance;
    instance = NULL;
  }
}
//---------------------------------------------------------------------------
